package com.inspectortime.webapp.util;

import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.inspectortime.webapp.inspector.EmailTemplateFormController;

public class ValidateLoggedInUserInterceptor implements HandlerInterceptor {

	private static Log log = LogFactory
			.getLog(ValidateLoggedInUserInterceptor.class);

	private String redirectPath;

	private String message;
	
	/**
	 * Output debug information to logs to help troubleshoot unexpected logout issues
	 */
	private boolean debugSessionUser = true;

	public void setDebugSessionUser(boolean debugSessionUser) {
		this.debugSessionUser = debugSessionUser;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public void setRedirectPath(String redirectPath) {
		this.redirectPath = redirectPath;
	}

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		if (RequestPathUtils.isProtectedPath(request)) {

			HttpSession session = request.getSession(false);
			if (session == null) {
				if (debugSessionUser) {
					log.debug(request.getServletPath() + ": Session not found");	
				}				
				redirectToLogin(request, response);
				return false;
			}
			Serializable userId = (Serializable) session
					.getAttribute(HttpSessionUtils.SESSION_ATTRIBUTE_USER_ID);
			if (userId == null) {
				if (debugSessionUser) {
					log.debug(request.getServletPath() + ": No user in session with id " + session.getId());	
				}
				redirectToLogin(request, response);
				return false;
			} else {
				if (debugSessionUser) {
					log.debug(request.getServletPath() + ": Found user id '" + userId + "' in session with id " + session.getId());	
				}
			}
		}
		return true;
	}

	private void redirectToLogin(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.sendRedirect(request.getContextPath() + this.redirectPath
				+ "?message=" + message);
	}

}
